<template>
  <div class="header-pack">
    <el-drawer v-model="drawerHeaderPack" title="选择标题" size="55%" class="native-anchor-drawer" direction="rtl" @close="handleDrawerClose(false)">
      <div class="header-pack-content">
        <div class="header-pack-content-item">
          <el-form :model="form" label-width="120px" label-position="left" :rules="rules" ref="formRef">
            <el-form-item label="标题来源" prop="headerPackLayout ">
              <el-radio-group v-model="headerPackLayout">
                <el-radio-button label="1"> 标题包 </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="标题分配方式" prop="fullAccountReuse">
              <el-radio-group v-model="fullAccountReuse" @change="handleFullAccountReuseChange">
                <el-radio-button label="1"> 全账户复用 </el-radio-button>
                <el-radio-button label="3"> 分账户配置 </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div class="userList" v-if="fullAccountReuse == '3'">
            <el-tabs v-model="curAccountIndex" class="demo-tabs" @tab-change="handleClick">
              <el-tab-pane v-for="(v, k) in accountList" :key="k" :label="v.name" :name="k"></el-tab-pane>
            </el-tabs>
          </div>

          <div class="header-pack-list" v-loading="loading">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="标题包名" prop="name">
                  <el-input v-model="queryParams.name" placeholder="请输入标题包名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
            <el-card shadow="hover">
              <template #header>
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oce:titleWrap:add']">新增</el-button>
                  </el-col>
                  <!-- <el-col :span="1.5">
                    <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oce:titleWrap:edit']"
                      >修改</el-button
                    >
                  </el-col>-->
                  <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" @click="handleDelete()" v-hasPermi="['oce:titleWrap:remove']">清除已选</el-button>
                  </el-col>
                  <!-- <el-col :span="1.5">
                    <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:titleWrap:export']">导出</el-button>
                  </el-col>
                  <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
                </el-row>
              </template>
              <el-table
                :data="titleWrapList"
                ref="tableRef"
                @row-click="handleRowClick"
                @select-all="handleSelectAll"
                @select="handleSelect"
                row-key="id"
              >
                <el-table-column type="selection" width="55" :reserve-selection="true" />
                <el-table-column prop="id" label="标题包ID" />
                <el-table-column prop="name" label="标题包名字" />
                <el-table-column label="操作" fixed="right" width="100">
                  <template #default="scope">
                    <el-button type="text" @click.stop="handleView(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-if="total > 0"
                v-model:total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="handleGetTitleWrapList()"
              />
            </el-card>
          </div>
        </div>
        <el-dialog v-model="isHeaderPackLibrary" title="标题列表" width="50%" append-to-body :close-on-click-modal="true">
          <div class="header-pack-library">
            <el-table :data="titleList" style="width: 100%" ref="titleTableRef">
              <el-table-column prop="id" label="ID" />
              <el-table-column prop="name" label="标题" />
            </el-table>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="isHeaderPackLibrary = false">关 闭</el-button>
            </span>
          </template>
        </el-dialog>
        <!-- 添加或修改标题包对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
          <el-form ref="titleWrapFormRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="标题包名" prop="name">
              <el-input v-model="form.name" placeholder="请输入标题包名" />
            </el-form-item>
            <el-form-item label="标题集合" prop="titles">
              <el-input v-model="form.titles" rows="6" type="textarea" placeholder="请输入标题集合，并以换行的方式分隔,每行字符长度为5-30" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDrawerClose(false)">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { getTitleWrapList, getTitleWrapListTitle } from '@/api/advertising/headerPack';
import { useAppStore } from '@/store/modules/app';
import { addTitleWrap, updateTitleWrap } from '@/api/advertisement/titleWrap';
import { confirmPromote } from '@/utils/index';
import { t } from 'vxe-table';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['drawerHeaderPack', 'accountList', 'headerPackList', 'titleWay']);
const emit = defineEmits(['update:drawerHeaderPack', 'selectedRows']);
const accountLists = ref([]);
const curAccountIndex = ref(0);
const appStore = useAppStore();
const selectedRows = ref([]); //选中行
const selectedVioIndex = ref('0');
const isHeaderPackLibrary = ref(false);
const buttonLoading = ref(false);
const tableRef = ref();
const drawerHeaderPack = ref(false);
const titleTableRef = ref<ElTableInstance>();
const titleWrapFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const headerPackLayout = ref('1'); //标题来源
const fullAccountReuse = ref(String(props.titleWay) || '1'); //全账号复用
const titleWrapList = ref([]); //标题包列表
const titleList = ref([]); //标题包下标题列表
const initFormData: any = {
  name: undefined,
  titles: undefined
};
const total = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const selectTitleList = ref([]);

const loading = ref(false);

const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    name: [{ required: true, message: '请输入标题包名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择素材类型', trigger: 'change' }]
  }
});
const { form, queryParams, rules, groupQos } = toRefs(data);

onMounted(() => {
  // drawerHeaderPack.value = props.drawerHeaderPack;
  // handleGetTitleWrapList();
});
watch(
  () => props.accountList,
  () => {
    accountLists.value = props.accountList.map((item, index) => {
      if (fullAccountReuse.value == '3') {
        selectTitleList.value[index] = [];
      }
      return {
        ...item,
        selectRow: []
      };
    });
  },
  { immediate: true }
);
//监听标题分配方式
watch(
  () => fullAccountReuse.value,
  () => {
    clearRows();
  }
);
watch(
  () => props.drawerHeaderPack,
  (val) => {
    drawerHeaderPack.value = val;
    nextTick(() => {
      handleGetTitleWrapList();
    });
  },
  { immediate: true }
);

watch(
  () => props.headerPackList,
  (newVal) => {
    if (newVal && newVal.length) {
      accountLists.value.map((item) => {
        props.headerPackList.map((subitem) => {
          if (fullAccountReuse.value == '3') {
            if (subitem.advertiserId === item.id && subitem.advertiserId) {
              const index = item.selectRow.findIndex((sub) => sub.id === subitem.id);
              if (index === -1) {
                item.selectRow.push(subitem);
              }
            }
          } else {
            const index = item.selectRow.findIndex((sub) => sub.id === subitem.id);
            if (index === -1) {
              item.selectRow.push(subitem);
            }
          }
        });
      });
    }
  },
  { immediate: true }
);

//监听标题列表
watch(
  () => titleWrapList.value,
  () => {
    if (props.headerPackList) {
      // tableRef.value?.clearSelection();
      // titleWrapList.value.forEach((item: any) => {
      //   if (fullAccountReuse.value == '1') {
      //     const index = accountLists.value[0].selectRow.findIndex((subitem) => subitem.id == item.id);
      //     if (index > -1) {
      //       setTimeout(() => {
      //         tableRef?.value.toggleRowSelection(item, true);
      //       }, 50);
      //     }
      //   } else if (fullAccountReuse.value == '3') {
      //     accountLists.value.map((item) => {
      //       item.selectRow.map((subitem) => {
      //         if (subitem.advertiserId === item.id && subitem.advertiserId) {
      //           const index = item.selectRow.findIndex((sub) => sub.id === subitem.id);
      //           if (index === -1) {
      //             item.selectRow.push(subitem);
      //           }
      //         }
      //       });
      //     });
      //     setTimeout(() => {
      //       const index = accountLists.value[curAccountIndex.value].selectRow.findIndex((subitem) => subitem.id == item.id);
      //       if (index > -1) {
      //         setTimeout(() => {
      //           tableRef?.value.toggleRowSelection(item, true);
      //         }, 50);
      //       }
      //     }, 50);
      //   }
      // });
    }
  }
);
watch(
  () => drawerHeaderPack.value,
  (val) => {
    emit('update:drawerHeaderPack', val);
  }
);
watch(
  () => props.titleWay,
  () => {
    nextTick(() => {
      fullAccountReuse.value = props.titleWay;
    });
  },
  { immediate: true }
);

const clearRows = () => {
  if (fullAccountReuse.value == '1') {
    selectTitleList.value = [];
  }
  accountLists.value.map((item, index) => {
    item.selectRow = [];
    selectTitleList.value[index] = [];
  });
};

/**
 * 清空已选
 */
const handleDelete = async () => {
  await confirmPromote({ content: '确定清空已选标题包吗？' });
  selectedRows.value = [];
  clearRows();
  tableRef?.value.clearSelection();
};

/**
 * 标题切换方式
 */
const handleFullAccountReuseChange = () => {
  tableRef?.value.clearSelection();
  curAccountIndex.value = 0;
  //将各账户选择的标题包初始化
  accountLists.value = accountLists.value.map((item) => {
    return {
      ...item,
      selectRow: []
    };
  });
};

/**
 * 切换用户选择标签
 */
const handleClick = () => {
  if (fullAccountReuse.value === '3') {
    tableRef?.value.clearSelection();
    if (accountLists.value[curAccountIndex.value].selectRow.length) {
      titleWrapList.value.map((item) => {
        const index = accountLists.value[curAccountIndex.value].selectRow.findIndex((subitem) => subitem.id == item.id);
        if (index > -1) {
          setTimeout(() => {
            tableRef?.value.toggleRowSelection(item, true);
          }, 50);
        }
      });
    } else {
      tableRef?.value.clearSelection();
    }
  }
};

/** 提交按钮 */
const submitForm = () => {
  // 根据换行来分割字符串
  form.value.titles = form.value.titles?.split('\n');
  form.value.titles = form.value.titles?.filter((item) => item);
  let isOk = true;
  form.value.titles.map((item) => {
    if (!isOk) return;
    if (item.length < 5 || item.length > 55) {
      isOk = false;
    }
  });
  if (!isOk) {
    proxy?.$modal.msgError('标题长度在5-55位之间');
    return;
  }

  titleWrapFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTitleWrap(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTitleWrap(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await handleGetTitleWrapList();
    }
  });
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  handleGetTitleWrapList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加标题包';
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  titleWrapFormRef.value?.resetFields();
};
// 查看
const handleView = (row: any) => {
  isHeaderPackLibrary.value = true;
  getTitleWrapListTitle({ id: row.id }).then((res) => {
    if (res.code === 200) {
      titleList.value = res.data;
    }
  });
};
const handleSelect = (selection: any, row: any) => {
  selectedRows.value = selection;
  if (selectedRows.value.length) {
    getSelectDatas();
  }
};
const handleSelectAll = (rows: any) => {
  selectedRows.value = rows;
  getSelectDatas();
};
const handleRowClick = (row: any) => {
  tableRef.value.toggleRowSelection(row);
  selectedRows.value = tableRef.value.getSelectionRows();
  // 获取选中数据
  getSelectDatas();
};

// 获取列表
const handleGetTitleWrapList = async () => {
  loading.value = true;
  const res = await getTitleWrapList(queryParams.value);
  titleWrapList.value = res.rows;
  total.value = res.total;
  // titleWrapList.value.forEach((item: any) => {
  //   const index =  props.headerPackList.findIndex((subitem) => subitem.id == item.id);
  //   if (index > -1) {
  //     tableRef?.value.toggleRowSelection(item, true);
  //   }
  // });
  loading.value = false;

  // getTitleWrapList(queryParams.value).then((res) => {
  //   if (res.code === 200) {
  //     titleWrapList.value = res.rows;
  //     nextTick(() => {
  //       titleWrapList.value.forEach((item: any) => {
  //         props.headerPackList &&
  //           props.headerPackList.forEach((item1: any) => {
  //             if (item.id == item1.id) {
  //               tableRef.value.toggleRowSelection(item, true);
  //             }
  //           });
  //       });
  //     });
  //   }
  // })
};
/**
 * 获取数据
 */
const getSelectDatas = () => {
  if (selectedRows.value.length) {
    selectedRows.value.map(async (item, index) => {
      const res = await getTitleWrapListTitle({ id: item.id });
      if (fullAccountReuse.value === '1') {
        selectTitleList.value[index] = res.data.map((subitem) => {
          return { title: subitem.name };
        });
      } else if (fullAccountReuse.value === '3') {
        // console.log('selectTitleList.value', selectTitleList.value);
        selectTitleList.value[curAccountIndex.value][index] = res.data.map((subitem) => {
          return { title: subitem.name };
        });
      }
    });
    if (fullAccountReuse.value === '3') {
      accountLists.value[curAccountIndex.value].selectRow = selectedRows.value;
    }
  } else {
    if (fullAccountReuse.value === '3') {
      accountLists.value[curAccountIndex.value].selectRow = [];
    }
  }
};

const handleSubmit = () => {
  /**
   * 数组组装
   */
  let data = [];
  let dataIsOk = true;
  if (fullAccountReuse.value == '1') {
    accountLists.value.map((item, index) => {
      if (!dataIsOk) return;
      if (selectedRows.value.length == 0) {
        dataIsOk = false;
      }
      selectedRows.value.map((subitem, subindex) => {
        data.push({
          advertiserId: item.id,
          id: subitem.id,
          name: subitem.name,
          titles: selectTitleList.value[subindex]
        });
      });
    });
  } else if (fullAccountReuse.value == '3') {
    accountLists.value.map((item, index) => {
      if (!dataIsOk) return;
      if (item.selectRow.length == 0) {
        dataIsOk = false;
      }
      item.selectRow.map((subitem, subindex) => {
        data.push({
          advertiserId: item.id,
          id: subitem.id,
          name: subitem.name,
          titles: selectTitleList.value[index][subindex]
        });
      });
    });
  }
  if (!dataIsOk) {
    proxy?.$modal.msgError(fullAccountReuse.value == '1' ? '检查是否已选择标题包' : '检查每个帐户是否都已选择标题包');
    return;
  }
  const datas = {
    titleWay: fullAccountReuse.value,
    data: data
  };
  curAccountIndex.value = 0;
  emit('update:drawerHeaderPack', false);
  emit('selectedRows', datas);
};
const handleDrawerClose = (val: boolean) => {
  drawerHeaderPack.value = val;
  emit('update:drawerHeaderPack', val);
};
</script>

<style scoped lang="scss">
.header-pack {
  .header-pack-content {
    padding: 0 20px;
    .header-pack-content-item {
      .el-radio-group {
        :deep(.el-radio-button__inner) {
          display: flex;
          flex-direction: column;
        }
        span {
          display: block;
          &:first-child {
            font-size: 14px;
            font-weight: 600;
            padding-bottom: 10px;
          }
          &:last-child {
            font-size: 12px;
          }
        }
      }
    }
    .header-pack-list {
      margin-top: 20px;
    }
  }
}
</style>
